package service

import (
	"server/global"
	"server/model"

	"gorm.io/gorm"
)

// add user
func UserAdd(user model.User) error {
	if err := global.DB.Create(&user).Error; err != nil {
		return err
	}
	return nil
}

// is exist
func UserIsExistById(u model.User) (bool, error) {
	var user model.User
	err := global.DB.Where("id = ?", u.ID).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if user.ID > 0 {
		return true, err
	}
	return false, nil
}

// is exist
func UserIsExist(u model.User) (bool, error) {
	var user model.User
	err := global.DB.Where("username = ?", u.Username).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if user.ID > 0 {
		return true, err
	}
	return false, nil
}

// get user by username
func UserGet(u model.User) (*model.User, error) {
	var user model.User
	err := global.DB.Where("username = ?", u.Username).First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &user, nil
}

// get all users
func UserGets() ([]*model.User, error) {
	var users []*model.User
	err := global.DB.Raw("SELECT * FROM users").Scan(&users).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return users, nil
}

// register
func UserRegister(u model.User) error {
	if err := global.DB.Create(&u).Error; err != nil {
		return err
	}
	return nil
}

// delete user
func UserDelete(u model.User) error {
	if err := global.DB.Where("username = ?", u.Username).Delete(model.User{}).Error; err != nil {
		return err
	}
	return nil
}

// edit user
func UserEdit(u model.User) error {
	if err := global.DB.Model(&model.User{}).Where("id = ?", u.ID).Save(&u).Error; err != nil {
		return err
	}
	return nil
}
